package com.roamer.audition.web.export.model;

import com.alibaba.excel.EasyExcel;
import com.roamer.audition.common.response.CompanyVO;
import com.roamer.audition.web.export.CompanyExcelService;
import com.roamer.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 消费者
 *
 * @author roamer
 * @version v1.0
 * @date 2019/10/13 17:30
 */
@Slf4j
public class Consumer extends Thread {

    private final ArrayBlockingQueue<List<CompanyVO>> queue;
    private int count;
    private int total;
    private SXSSFWorkbook sxssfWorkbook;
    private int times;

    public Consumer(ArrayBlockingQueue<List<CompanyVO>> queue, SXSSFWorkbook sxssfWorkbook, int total) {
        this.queue = queue;
        this.total = total;
        this.count = 0;
        this.sxssfWorkbook = sxssfWorkbook;
        this.times = 1;
    }

    @Override
    public void run() {
        try {
            while (true) {
                if (count >= total) {
                    break;
                }
                log.info(String.format("消费者第[%s]次从队列中取出数据，准备写入Excel", this.times));
                Long dataWriteStartTS = System.currentTimeMillis();
                List<CompanyVO> companyVOList = queue.take();
                log.info("消费者线程[{}]成功获取[{}]条数据，在队列阻塞：[{}}ms]", this.getName(), companyVOList.size(),
                        System.currentTimeMillis() - dataWriteStartTS);

                // 根据总条数确定消费者本次写入数据时的开始行数
                int index = count % CompanyExcelService.MAX_ROW_SHEET == 0 ? (count + 2) : (count % CompanyExcelService.MAX_ROW_SHEET + 2);
                count = count + companyVOList.size();
                // 计算sheet
                int sheetNum = count / CompanyExcelService.MAX_ROW_SHEET;

                if (CollectionUtils.isEmpty(companyVOList)) {
                    log.info(String.format("消费者[%s]: 数据为空", this.getName()));
                    return;
                }

                EasyExcel.writerSheet(sheetNum, "日期").doWrite(companyVOList);
                Sheet sheet = sxssfWorkbook.getSheetAt(sheetNum);
                Long dataWriteEndTS = System.currentTimeMillis();
                log.info(String.format("消费者第[%s]次写入Excel完成，耗时%s ms", this.times, (dataWriteEndTS - dataWriteStartTS)));
                this.times++;
            }
        } catch (InterruptedException e) {
            log.error("消费者[%s]获取队列数据异常-->", e);
        }
    }

}
